<template>
    <div class="models-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <List />
                        </el-icon>
                        <span>模型管理</span>
                    </div>
                    <div class="header-right">
                        <el-select v-model="filterType" placeholder="按类型筛选" clearable class="filter-select">
                            <el-option label="全部" value="" />
                            <el-option label="文本模型" :value="0" />
                            <el-option label="视觉模型" :value="1" />
                        </el-select>
                        <el-button type="primary" @click="handleAdd">添加模型</el-button>
                    </div>
                </div>
            </template>

            <el-table :data="filteredModelList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="name" label="模型名称" />
                <el-table-column prop="type" label="类型">
                    <template #default="{ row }">
                        <el-tag :type="getTagType(row.type)">
                            {{ getModelType(row.type) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="状态" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.state" :active-value="1" :inactive-value="0"
                            @change="(val) => handleStatusChange(row, val)" />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button type="primary" link @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" destroy-on-close>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="模型名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入模型名称" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择模型类型">
                        <el-option label="文本模型" :value="0" />
                        <el-option label="视觉模型" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.state" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialog.visible = false">取 消</el-button>
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { List } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const modelList = ref([])
const filterType = ref('')
const formRef = ref(null)

// 获取模型列表
const getModelList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/model/list',
            method: 'get'
        })
        modelList.value = res.data
    } catch (error) {
        console.error('获取模型列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 对话框相关
const dialog = reactive({
    visible: false,
    title: ''
})

const form = reactive({
    id: null,
    name: '',
    type: 0,
    state: 1
})

const rules = {
    name: [
        { required: true, message: '请输入模型名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择模型类型', trigger: 'change' }
    ]
}

// 获取标签类型
const getTagType = (type) => {
    return type === 1 ? 'success' : ''
}

// 获取模型类型文本
const getModelType = (type) => {
    const typeMap = {
        0: '文本模型',
        1: '视觉模型'
    }
    return typeMap[type] || '未知类型'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 添加模型
const handleAdd = () => {
    dialog.title = '添加模型'
    dialog.visible = true
    form.id = null
    form.name = ''
    form.type = 0
    form.state = 1
}

// 编辑模型
const handleEdit = (row) => {
    dialog.title = '编辑模型'
    dialog.visible = true
    Object.assign(form, row)
}

// 删除模型
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确认删除该模型吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await request({
                url: `/model/delete/${row.id}`,
                method: 'delete'
            })
            ElMessage.success('删除成功')
            getModelList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

// 切换状态
const handleStatusChange = async (row, value) => {
    try {
        await request({
            url: `/model/state/${row.id}`,
            method: 'put',
            data: { state: value }
        })
        ElMessage.success('状态更新成功')
    } catch (error) {
        row.state = value === 1 ? 0 : 1 // 恢复状态
        console.error('状态更新失败:', error)
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        const isEdit = !!form.id

        await request({
            url: `/model/${isEdit ? 'update' : 'add'}`,
            method: isEdit ? 'put' : 'post',
            data: form
        })

        ElMessage.success(`${isEdit ? '编辑' : '添加'}成功`)
        dialog.visible = false
        getModelList()
    } catch (error) {
        console.error('保存失败:', error)
    }
}

// 计算筛选后的列表
const filteredModelList = computed(() => {
    if (filterType.value === '') {
        return modelList.value
    }
    return modelList.value.filter(model => model.type === filterType.value)
})

onMounted(() => {
    getModelList()
})
</script>

<style scoped>
.models-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.dialog-footer {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

:deep(.el-tag) {
    text-transform: capitalize;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

.filter-select {
    width: 120px;
}
</style>